<?php
/**
 * Implementation of PPA for Outlet ORM
 * 
 * @package    Lazy Framework
 * @subpackage ppa
 * @author     Eduardo Marcolino <eduardo.marcolino@gmail.com>
 * @version    0.0.1
 */

class PPAOutletORMImpl{
	
	private $entity = null;
	
	public function __construct($model_dir)
	{
		foreach (glob($model_dir."/*.php") as $filename) 
		{
			require_once($filename);
			$associations = array();
	
			$class_name = current(explode('.',end(explode('/',$filename))));
			$r = new ReflectionAnnotatedClass($class_name);
	
			if ($r->hasAnnotation('Entity')) 
			{
				$this->entity[$class_name] = array();
				$this->entity[$class_name]['table'] = $r->hasAnnotation('Table') ? $r->getAnnotation('Table')->value : strtolower($class_name);
		
				$props = array();
				foreach($r->getProperties() as $p) 
				{
					if($p->hasAnnotation('Column')) 
					{
						$props[$p->name] = array($p->getAnnotation('Column')->name, $p->getAnnotation('Column')->type);
										 
						if($p->hasAnnotation('Id')) 
						{
							array_push($props[$p->name],
								array('pk'=>true, 'autoIncrement'=>$p->getAnnotation('Id')->autoIncrement));
						}
					}
					
					$assoc = null;
					if($p->hasAnnotation('OnetoMany')) { $assoc = $p->getAnnotation('OnetoMany'); }
					if($p->hasAnnotation('ManyToOne')) { $assoc = $p->getAnnotation('ManyToOne');}
					if (!is_null($assoc)) 
					{
						array_push($associations,
							array($assoc->getType(),$assoc->entity,array('key'=>$assoc->key)));
					}
				}
		
				$this->entity[$class_name]['props'] = $props;
				$this->entity[$class_name]['associations'] = $associations;
		
			}
		}
	}
	
	public function hasEntities() {
		return !is_null($this->entity);
	}
	
	public function getClasses() {
		return 	array('classes' => $this->entity);	
	}
}